<?php

class MyDB{
	var $connection = null;
	private static $_instance = null;


	public static function getInstance()
	{
		if(!isset(self::$_instance))
		{
			$c=__CLASS__;
			self::$_instance=new $c;
		}
		return self::$_instance;
	}

	private function __construct(){
		$this->_openConn();
	}

	private function _openConn(){
		$this->connection = mysql_connect(DB_HOST.":".DB_PORT,DB_USER,DB_PASS)
		or die("Can not connect to mysql:".mysql_errno());
		
		mysql_select_db(DB_NAME) or die('Can NOT change to database "{$DB_NAME}":'.mysql_error());
		return $this->connection;
	}

	public function openConn(){
		return $this->connection;
	}

	public function closeConn(){
		mysql_close($this->connection);
	}


	public function queryOneValue($sql){
		log_sql($sql);
		$result = mysql_query($sql,$this->connection) or die(mysql_error());
		$row = mysql_fetch_row($result);
		if($row[0]){
			return  $row[0];
		}else{
			return FALSE;
		}
	}
	
	public function queryOneRow($sql){
		log_sql($sql);
		//TODO 可以再这里添加limit语句检查，必要时加上此语句，可以一定概率避免不必要的查询。
		$ret = mysql_query($sql,$this->connection) or die(mysql_error());
		return mysql_fetch_array($ret,MYSQL_ASSOC);
	}

	public function insertOneRecord($sql){
		log_sql($sql);
		//TODO 检查是否包含insert开头的语句，否则报错
		mysql_query($sql,$this->connection) or die(mysql_error());
		$id = mysql_insert_id($this->connection);
		return $id;
	}

	public function exec($sql){
		log_sql($sql);
		$result = mysql_query($sql, $this->connection) or die(mysql_error($this->connection));
		if($result){
			return $result;
		}else{
			dumpError("{$sql}<br />SQL执行错误: " . mysql_error($this->connection));
		}
	}

	/**
	 * 对特殊字符进行过滤
	 *
	 * @param value  值
	 */
	public function __val_escape($value) {
		if(is_null($value))return 'NULL';
		if(is_bool($value))return $value ? 1 : 0;
		if(is_int($value))return (int)$value;
		if(is_float($value))return (float)$value;
		if(@get_magic_quotes_gpc())$value = stripslashes($value);
		return '\''.mysql_real_escape_string($value, $this->conn).'\'';
	}

	/**
	 * 析构函数
	 */
	public function __destruct()
	{
		@mysql_close($this->connection);
	}
}